package com.education.admin.api.controller;

import com.education.common.utils.ObjectUtils;
import com.education.common.utils.Result;
import com.education.common.utils.ResultCode;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * 文件上传接口
 * @author 余一
 * @date 2021/9/5  16:30
 */
@RestController
public class UploadController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
    //上传的文件类型
    private static final int IMAGE_FILE = 1; //图片文件
    private static final int VIDEO_FILE = 2;//视频文件
    private static final int OTHER_FILE = 3; //其他文件
    //文件的根路径
    @Value("${file.upload}")
    private String basePath;

    //图片格式
    private static final Set imageContentType = new HashSet(){
        {
            add("image/jpeg");
            add("image/jpg");
            add("image/png");
            add("image/gif");
            add("image/x-png");
        }
    };

    @RequestMapping(value = "/upload/{uploadFileType}",method = RequestMethod.POST)
    public Result upload(@RequestParam MultipartFile file, @PathVariable int uploadFileType){
        Result result = this.checkImageFile(file);
        if (!result.isSuccess()) {
            return result;
        }
        String originalFilename = file.getOriginalFilename();//获取文件原名
        String suffix = "." + FilenameUtils.getExtension(originalFilename);
        String uploadPath = null;
        switch (uploadFileType){
            case IMAGE_FILE:
                uploadPath = createImagePath(suffix);
                break;
            case VIDEO_FILE:
                break;
            case OTHER_FILE:
                break;
        }
        if (ObjectUtils.isNotEmpty(uploadPath)) {
            try{
                String filePath = basePath + uploadPath;
                File uploadFile = new File(filePath);
                if (!uploadFile.exists()) {
                    uploadFile.getParentFile().mkdirs();
                }
                file.transferTo(uploadFile);//将文件上传到uploadFile文件目录

                result.setCode(ResultCode.SUCCESS);
                result.setMessage("文件上传成功！");
                result.setData(uploadPath);
            }catch (IOException e){
                logger.error("文件上传异常："+e.getMessage());
                result.setCode(ResultCode.FAIL);
                result.setMessage("文件上传失败！");
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 创建图片路径
     * @param suffix 图片的后缀名
     * @return
     */
    private String createImagePath(String suffix) {
        return "/images/" + ObjectUtils.generateFileByTime() + ObjectUtils.generateUuId()
                + suffix;
    }

    /**
     * 校验图片类型和大小
     * @param file
     * @return
     */
    private Result checkImageFile(MultipartFile file){
        String contentType = file.getContentType();// 获取文件content-type
        if (!imageContentType.contains(contentType)){
            return Result.fail(ResultCode.FAIL,"图片格式错误，只能上传PNG/JPG格式，请重新上传");
        }
        long fileSize = file.getSize();
        if (fileSize > 1024 * 1024) {
            return Result.fail(ResultCode.FAIL,"图片大小不能超过1MB");
        }
        return new Result();
    }

    @DeleteMapping("deleteFile")
    public Result deleteFile(@RequestParam String url){
        File file = new File(basePath + url);
        if (file.exists()) {
            file.delete();
            return Result.success(ResultCode.SUCCESS,"删除成功");
        }
        return Result.fail(ResultCode.FAIL,"文件不存在或已删除");
    }
}
